import { LoginFormData, getUserInfoAPI, loginAPI } from '@/apis/userApi';
import { deleteToken, getToken, setToken } from '@/utils/tokenUtil';
import { Dispatch, createSlice } from '@reduxjs/toolkit';
import { message } from 'antd';

const EMPTY_USERINFO = { id: '', photo: '', name: '', mobile: '', gender: 1, birthday: '' };

// 用户信息管理片
const userSlice = createSlice({
    name: 'user',
    // 初始化token
    initialState: {
        token: getToken() || '',
        userInfo: EMPTY_USERINFO,
    },
    reducers: {
        // 设置登录token
        setUserData(state, action) {
            state.token = action.payload;
            // 持久化登录token
            setToken(state.token);
        },
        // 设置用户信息
        setUserInfo(state, action) {
            state.userInfo = action.payload;
        },
        // 注销登录
        clearAll(state) {
            state.token = '';
            state.userInfo = EMPTY_USERINFO;
            deleteToken();
        },
    },
});

// action creator
export const { setUserData, setUserInfo, clearAll } = userSlice.actions;

// 登录thunk creator
export const fetchLogin = (formData: LoginFormData) => {
    return async (dispatch: Dispatch) => {
        const response = await loginAPI(formData).request;
        // 记录登录token
        dispatch(setUserData(response.data.token));
    };
};

// 获取用户信息thunk creator
export const fetchUserInfo = () => {
    return async (dispatch: Dispatch) => {
        const response = await getUserInfoAPI().request;
        // 记录用户信息
        dispatch(setUserInfo(response.data));
        message.success(`欢迎回来！${response.data.name}`);
    };
};

// reducer函数
export default userSlice.reducer;
